class Requirement < ActiveRecord::Base
  belongs_to :user
  belongs_to :retype
  belongs_to :solver,
             :class_name => 'User',
             :foreign_key => 'solver_id'
  
  has_many :comments, :order => "created_at", :dependent => :destroy
  
  has_many :favorite_requirements
  has_many :lovers,
           :through => :favorite_requirements,
           :source => :user
  
  has_many :requirement_orders
  has_many :orders,
           :through => :requirement_orders,
           :source => :user
           
  has_attached_file :attach, 
                          :path => ":rails_root/public/:class/:attachment/:id/:style_:basename.:extension",
                          :url  => "/:class/:attachment/:id/:style_:basename.:extension"
#  before_post_process :image?
#  def image?
#    !(data_content_type =~/^image.*/).nil?
#  end                   
  after_save :update_counter_cache     
  attr_protected :attach_file_size, :attach_content_type
  validates_attachment_size :attach, :less_than => 5.megabytes, :message => "附件不超过5m"
  validates_attachment_content_type :attach, :content_type => ['application/zip','application/rar'], :message => "请上传zip或rar文件"
  
  validates_presence_of :title, :content, :price, :message => "不能为空"
  validates_numericality_of :price, :message => "为数字"
  validates_uniqueness_of :content, :scope => [:user_id,:title]
  
  define_index do
    indexes title
    indexes content
    has user_id, created_at, updated_at
  end
  
  def duplicate?
    re = Requirement.find_by_user_id_and_title_and_content(user_id,title,content)
    self.id = re.id unless re.nil?
    not re.nil?
  end
  
  def solver_exists?
    not self.solver.nil?
  end
  
  private 
  def update_counter_cache
    update_attribute(:comments_count, self.comments.length) unless self.comments_count.to_i == self.comments.length
  end
  
end
